const express = require('express');
const path = require('path');
const automator = require('miniprogram-automator');
const URI = require('urijs');
const { pathTransverter } = require('./pathTransverter');
const app = express();
const result = require('./result.json');
const crypto = require('crypto');
const fs = require("fs");
const { mode, apiUrl, cityId, platform} = require('./config')
app.set('view engine', 'ejs');
app.set('views', `${__dirname}/views`);
app.use(express.static(path.join(__dirname, 'screenshots')));
const XLSX = require("xlsx");
const workbook = XLSX.readFile(path.resolve(__dirname, 'path.xlsx'), {});
const sheetName = workbook.SheetNames[0]
const jsData = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])

const TAG = mode; // 1 城市版 2 全国版
const testPaths = jsData.map(item => {
    return {
        title: item['页面标题'],
        path: '/' + item.url
    }
})
const OLD_TAB_PATH = ['/pages/index', '/pages/project/index', '/pages/consult/index', '/pages/me/advisory']
const TAB_PAGES = ['/pages/index/index', '/pages/find/index', '/pages/consult/index', '/pages/im/index', '/pages/me/index', ...OLD_TAB_PATH];
function isTabBarPage (url) {
    return TAB_PAGES.some(path => url.startsWith(path));
}
let num = 1;

const hasFile = (file) => {
    return new Promise(resolve => {
        console.log(file)
        fs.exists(file, (exists) => {
            resolve(exists)
        });
    })
}


automator.connect({
    wsEndpoint: 'ws://localhost:9420'
}).then(async miniProgram => {
    miniProgram.on('exception', err => {
        console.log(err.message, err.stack)
    })
    for (let i = 0; i < testPaths.length; i++) {
        try {
            let imagePath = '';
            const testPath = testPaths[i].path;
            const hash = crypto.createHash('md5').update(testPath).digest('hex');
            const filePath = path.resolve(__dirname, `./screenshots/${TAG === 1 ? 'old' : 'new'}_${hash}.png`)
            const hasExist = await hasFile(filePath)
            if (hasExist) {
                console.log(`已有截图，跳过${i + 1} / ${testPaths.length}`)
                continue
            }
            if (TAG === 1) {
                imagePath = `src/screenshots/old_${hash}.png`;
            } else {
                imagePath = `src/screenshots/new_${hash}.png`;
            }

            const oldUriObj = new URI(testPath);
            let url = ''
            if (mode === 1) {
                url = testPath
            } else {
                const { data } = await pathTransverter(oldUriObj.path(), oldUriObj.search(true));
                url = data.data.path;
            }
            const params = {
                path: oldUriObj.path(),
                query: oldUriObj.search(true)
            }
            const cmd = `curl '${apiUrl + '?city_id=' + cityId}' \\
        -H 'Platform: 1' \\
        --data-binary '${JSON.stringify(params)}' \\
        `

            let page = null;
            const newPathObj = new URI(url);
            const newPathQuery = newPathObj.search(true);
            if (newPathQuery && newPathQuery.redirect) {
                url = newPathQuery.redirect;
            }
            if (isTabBarPage(url)) {
                page = await miniProgram.switchTab(url);
            } else {
                page = await miniProgram.redirectTo(url);
            }




            await page.waitFor(3500)
            await miniProgram.screenshot({
                path: imagePath
            });
            console.log(`正在截屏${i + 1} / ${testPaths.length}`)
            num++;
            const idx = result.data?.findIndex(item => item.title === testPaths[i].title);
            if (idx > -1) {
                if (TAG === 1) {
                    result.data[idx].old = imagePath
                } else {
                    result.data[idx].new = imagePath
                }
                result.data[idx].new_path = url;
                result.data[idx].old_path = testPath;
                result.data[idx].curl = cmd;
            } else {
                const item = {
                    title: testPaths[i].title
                }
                if (TAG === 1) {
                    item.old = imagePath
                } else {
                    item.new = imagePath
                }
                item.new_path = url;
                item.old_path = testPath;
                item.curl = cmd;
                result.data.push(item)
            }
            const resultJsonFile = `result.json`
            fs.writeFileSync(path.resolve(__dirname, resultJsonFile), JSON.stringify(result, null, '\t'))
        } catch (e) {
            console.error(e)
        }
    }
    console.log('完成截屏')
    process.exit()
});
